<template>
  <div class="x-handle" @mousedown="mouseDown"></div>
</template>
<script>
export default {
  name: 'cDrag',
  data() {
    return {
      lastX: ''
    }
  },
  created() {
    document.addEventListener('mouseup', this.mouseUp)
  },
  destroyed() {
    document.removeEventListener('mouseup', this.mouseUp)
  },
  methods: {
    mouseDown(event) {
      document.addEventListener('mousemove', this.mouseMove)
      this.lastX = event.screenX
    },
    mouseMove(event) {
      event.preventDefault()
      if (event.buttons) { // 按下
        this.$emit('widthChange', this.lastX - event.screenX)
        this.lastX = event.screenX
      } else { // 松开
        // 由于其他原因此时鼠标已经松开没有触发mouseup - 手动移除
        this.mouseUp()
      }
    },
    mouseUp() {
      this.lastX = ''
      document.removeEventListener('mousemove', this.mouseMove)
    }
  }
}
</script>
<style lang="scss">
.x-handle {
  width: 3px;
  margin: 0 5px;
  cursor: w-resize;
  z-index: 10;
  background: #ccc;
}
</style>
